package com.yanggu.scala.chapater11.reduce

object ReduceDemo01 {

  def main(args: Array[String]): Unit = {
    //看一个需求:
    //val list = List(1, 20, 30, 4 ,5) , 求出list的和.
    val list = List(1, 20, 30, 4, 5)
    println(list.sum)
    //说明
    //def reduceLeft[B >: A](@deprecatedName('f) op: (B, A) => B): B
    //reduceLeft(f) 接收的函数需要的形式为 op: (B, A) => B): B
    //reduceleft(f) 的运行规则是 从左边开始执行将得到的结果返回给第一个参数
    // 然后继续和下一个元素运行，将得到的结果继续返回给第一个参数，继续..
    //即: //((((1 + 2)  + 3) + 4) + 5) = 15

    val list2 = List(1, 2, 3, 4, 5)

    def minus(num1: Int, num2: Int): Int = {
      num1 - num2
    }
    //1 - 2 - 3 - 4 - 5 = -13
    //reduce底层就是调用reduceLeft
    println(list2.reduce(minus))
    //1 - 2 - 3 - 4 - 5 = -13
    println(list2.reduceLeft(minus))
    //1 - (2 - (3 - (4 - 5))) = 3
    println(list2.reduceRight(minus))
  }

}
